/**
 * Whistle Rules Server
 * 负责动态提供当前激活的代理规则
 */

const DataStorage = require('./dataStorage');

module.exports = (server, options) => {
  console.log('[Switcher3] 初始化 Rules Server');
  
  // 初始化数据存储
  const dataStorage = new DataStorage(options.storage);
  
  server.on('request', (req, res) => {
    try {
      console.log('[Switcher3] RulesServer 收到规则请求');
      
      // 生成当前激活环境的规则
      const rules = generateActiveRules(dataStorage);
      
      console.log('[Switcher3] 生成的规则:', rules);
      
      // 设置响应头
      res.setHeader('Content-Type', 'text/plain; charset=utf-8');
      res.setHeader('Cache-Control', 'no-cache');
      
      // 返回规则文本
      res.end(rules);
      
    } catch (error) {
      console.error('[Switcher3] RulesServer 错误:', error);
      res.statusCode = 500;
      res.end('# Switcher3 Rules Server Error\n');
    }
  });
};

/**
 * 生成当前激活环境的所有规则
 */
function generateActiveRules(dataStorage) {
  const rules = [];
  
  // 添加规则头部注释
  rules.push('# Switcher3 Plugin Rules');
  rules.push('# Generated at: ' + new Date().toISOString());
  rules.push('');
  
  try {
    // 获取所有项目的激活环境
    const activeEnvironments = dataStorage.getActiveEnvironments();
    console.log('[Switcher3] 激活的环境:', activeEnvironments);
    
    if (activeEnvironments.length === 0) {
      rules.push('# No active environments');
      return rules.join('\n');
    }
    
    // 为每个激活的环境生成规则
    activeEnvironments.forEach(env => {
      const project = dataStorage.getProject(env.projectId);
      if (!project) {
        console.log(`[Switcher3] 项目不存在: ${env.projectId}`);
        return;
      }
      
      rules.push('');
      rules.push(`# Project: ${project.name}`);
      rules.push(`# Environment: ${env.environment}`);
      rules.push(`# Project ID: ${env.projectId}`);
      
      // 获取环境配置
      let configContent = '';
      if (env.environment === 'test') {
        configContent = project.environments.test;
      } else if (env.environment === 'production') {
        configContent = project.environments.production;
      } else if (env.environment.startsWith('custom:')) {
        const ruleId = env.environment.substring(7);
        const rule = project.customRules.find(r => r.id === ruleId);
        if (rule) {
          configContent = rule.value;
        }
      }
      
      if (configContent && configContent.trim()) {
        // 解析配置内容并生成规则
        const configLines = configContent.split('\n');
        
        configLines.forEach(line => {
          line = line.trim();
          
          // 跳过空行和注释行
          if (!line || line.startsWith('#')) {
            if (line) {
              rules.push(line); // 保留用户的注释
            }
            return;
          }
          
          // 解析域名映射规则（用户输入格式：IP地址 域名）
          const parts = line.split(/\s+/);
          if (parts.length >= 2) {
            const target = parts[0];  // IP地址
            const domain = parts[1];  // 域名
            
            // 生成Whistle规则格式（域名 IP地址）
            const whistleRule = `${domain} ${target}`;
            rules.push(whistleRule);
          }
        });
      } else {
        rules.push(`# ${project.name} - ${env.environment}: No configuration`);
      }
    });
    
  } catch (error) {
    console.error('[Switcher3] 生成规则失败:', error);
    rules.push('# Error generating rules: ' + error.message);
  }
  
  return rules.join('\n');
}